/**
 * @ngdoc controller
 * @name file-search
 * @description
 * # Application_NG：文件查询
 */
(function () {
    'use strict';
    appModule.controller('file-search', [
        '$scope', '$uibModal', 'toastr', '$state', '$q', '$http', '$location', '$stateParams',

        function ($scope, $uibModal, toastr, $state, $q, $http, $location, $stateParams) {
            console.log('查询页');
            $scope.httpUrl = API_SERVICE_AMBAR + "api/files/1.jpg";
            $scope.searchText = ""; //查询值
            $scope.searchType = ""; //查询类型
            $scope.searchFilter = {}; //查询条件
            $scope.byDate = [];//按照时间过滤
            $scope.byType = [];//按照文件类型过滤
            $scope.byTag = [];//按照文件标签过滤
            $scope.byFolder = [];//按照文件库过滤
            $scope.tableData = [];//查询内容
            $scope.showType = ""; //显示类型
            $scope.API_SERVICE_AMBAR = API_SERVICE_AMBAR; //文件路径
            var zTree_Menu, curMenu;
            $scope.parentNodeId = null;

            $scope.showType = 'Table'
            $scope.searchFilter = { time: "all", type: "all", tag: "", folder: [] }
            $scope.byDate = [{
                value: 'all',
                spanValue: '查看全部'
            }, {
                value: 'today',
                spanValue: '今天',
            }, {
                value: 'yesterday',
                spanValue: '昨天',
            }, {
                value: 'thisweek',
                spanValue: '近一周',
            }, {
                value: 'thismonth',
                spanValue: '近一个月',
            }, {
                value: 'thisyear',
                spanValue: '近一年度',
            }];
            $scope.byType = [{
                value: 'all',
                spanValue: '查看全部',
            }, {
                value: 'word',
                spanValue: 'Word文档',
            }, {
                value: 'pdf',
                spanValue: 'pdf文档',
            }, {
                value: 'data',
                spanValue: '数据文件',
            }, {
                value: 'txt',
                spanValue: '文本文档',
            }, {
                value: 'img',
                spanValue: '图片文件',
            }];
            $scope.pointlist = [{
                id: '1',
                name: '昆明网安',
                quantity: 10000
            }, {
                id: '2',
                name: '盘龙网安',
                quantity: 500
            }, {
                id: '3',
                name: '曲靖网安',
                quantity: 800
            }, {
                id: '4',
                name: '东川网安',
                quantity: 5456

            }];

            // $scope.wordCssto=""
            $scope.wordCss = ["txt", "docx", "doc", "csv", "html", "pdf", "md", "json", "jpg", "png", "gif"];



            var fn = function (msg) {
                var deffer = $q.defer();
                deffer.resolve(msg);
                return deffer.promise;
            };



            //获取index页面传过来的值
            $scope.searchText = null;
            if ($stateParams.paramsObj) {
                $scope.searchText = $stateParams.paramsObj.searchText;
                $scope.searchType = $stateParams.paramsObj.searchType == 1 ? true : false;
                $location.search({
                    'searchText': $stateParams.paramsObj.searchText,
                    'searchType': $stateParams.paramsObj.searchType ? 1 : 0
                });
            } else {
                $scope.searchText = $location.search().searchText;
                $scope.searchType = $location.search().searchType == 1 ? true : false;
                // console.log($scope.searchText);
                // console.log($scope.searchType);
            }

            // 列表分页配置
            $scope.paginationConf = {
                'currentPage': $location.search().currentPage ? $location.search().currentPage : 1, //当前页
                'itemsPerPage': $location.search().itemsPerPage ? $location.search().itemsPerPage : 5, //每页显示的数量
                'perPageOptions': [10, 20, 50, 100], //每页显示多少条数据的选项
            };
            // 监控分页
            $scope.$watch('paginationConf.currentPage + paginationConf.itemsPerPage', function () {
                $location.search({
                    'searchText': $scope.searchText,
                    'searchType': $scope.searchType ? 1 : 0,
                    'currentPage': $scope.paginationConf.currentPage,
                    'itemsPerPage': $scope.paginationConf.itemsPerPage
                });
                /* 
                    判断内容是否为空，避免搜索内容为空时，调用getResultData向服务器发送请求
                */
                if ($scope.searchText) {
                    $scope.search()
                }
            });
            // 监控查询内容
            $scope.$watch('searchText', function () {
                if ($scope.searchText == "" || $scope.searchText == "*") {
                    $scope.searchType = false
                }

            });
            $scope.$watch('searchType', function () {
                console.log($scope.searchType);
            });
            // zTree配置
            $scope.treeSetting = {
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "path",
                        pIdKey: "parent_path",
                        rootPId: 0
                    },
                    key: {
                        title: "title"
                    }
                },
                view: {
                    nameIsHTML: true,
                    showIcon: false,
                    showLine: true,
                    showTitle: true,
                    selectedMulti: false,
                    dblClickExpand: false
                },
                callback: {
                    // 鼠标左键触发事件
                    onClick: function (e, treeId, treeNode) {
                        console.log("treeNode.folderName", treeNode.folderName)
                        fn(treeNode).then(function (treeNode) {
                            if (treeNode.folderName == $scope.searchFilter.folder) {

                            } else {
                                $scope.searchFilter.folder = treeNode.folderName
                                if ($scope.paginationConf.currentPage != 1) {
                                    $scope.paginationConf.currentPage = 1;
                                } else {
                                    $scope.search()
                                }
                            }
                        });
                    },
                    // onNodeCreated: onNodeCreated,
                    beforeClick: beforeClick,
                }
            };

            function beforeClick(treeId, node) {
                if (node.isParent) {
                    // $(".ztree li a.level0.cur").removeAttr("style", "");
                    if (node.level === 0) {
                        $scope.parentNodeId = node.tId; //一级目录Id
                        $(".ztree li a.level0.cur").removeAttr("style", "");
                        var pNode = curMenu;
                        console.log("pNode", pNode)
                        console.log("node", node)
                        var a = $("#" + pNode.tId + "_a");
                        a.removeClass("cur");
                        while (pNode && pNode.level !== 0) {
                            pNode = pNode.getParentNode();
                        }
                        // console.log(pNode, node)
                        if (pNode !== node) {
                            var a = $("#" + pNode.tId + "_a");
                            a.removeClass("cur");
                            zTree_Menu.expandNode(pNode, false);
                        }
                        a = $("#" + node.tId + "_a");
                        a.addClass("cur");
                        if ($(".ztree li a.level0").hasClass("cur")) {
                            $(".ztree li a.level0 span").removeAttr("style", "");
                            $(".ztree li a.level0.cur span").css({ "color": "#fff" });
                        }
                        if ($("#" + node.tId + "_a").hasClass("hasChildren")) {
                            $("#" + node.tId + "_a.cur").removeAttr("style", "");
                            // $("#" + node.tId + "_a.cur").css({ "box-shadow": "1px 4px 11px black", "margin-bottom": "8px" });
                            $("#" + node.tId + "_a.cur").css({"margin-bottom": "8px" });
                        }
                        // $("#" + node.tId + "_a.cur").css({ "border-bottom": "2px solid #3468b5"});

                        $("#" + node.tId + "_a.cur").css({ "background-color": "#337ab7"}); //点击之后，添加背景颜色
                        $("#" + node.tId + "_a.cur span span.dataNumByFolder").css({ "color": "#fff"}); //将显示数量的文字设置为白色
                        // $("#" + node.tId + "_a.cur").children(".node_name").children().removeAttr("style", "");
                        /* 
                            重新绑定hover事件，这是为了避免在点击其他的一级目录后，当前点击的一级目录显示数量的文字hover事件失效
                        */
                        var a0 = $(".ztree li a span.node_name");
                        a0.hover(function(){
                            $(this.children).css({"color":"#fff"});
                        },function(){
                            $(this.children).css({"color":"red"});
                        });
                        // 当前点击的一级目录显示数量的文字取消绑定hover事件
                        $("#" + node.tId + "_a.cur").children(".node_name").unbind("mouseenter").unbind("mouseleave");
                        $("#" + node.tId + "_a.cur").children(".node_name").children().css({ "color": "#fff" });

                        var isOpen = false;
                        for (var i = 0, l = node.children.length; i < l; i++) {
                            if (node.children[i].open) {
                                isOpen = true;
                                break;
                            }
                        }
                        if (isOpen) {
                            zTree_Menu.expandNode(node, true);
                            curMenu = node;
                        } else {
                            if (node.children.length > 0) {
                                zTree_Menu.expandNode(node.children[0].isParent ? node.children[0] : node, true);
                                curMenu = node.children[0];
                            } else {
                                curMenu = node
                            }
                        }
                    } else {
                        zTree_Menu.expandNode(node);
                        // if ($(".ztree li ul li a").checked = true) {
                        //     $(".ztree li a.level0.cur").css({ "background": "#48b6f8" });
                        // }

                        /* 
                            点击一级目录下的子目录，取消绑定一级目录的hover事件，同时将一级目录显示数量的文字设置成白色
                        */
                        $("#" + $scope.parentNodeId + "_a.cur").unbind("mouseenter").unbind("mouseleave");
                        $("#" + $scope.parentNodeId + "_a.cur").children().children().css({"color": "#fff"});
                    }

                }
                console.log("node", node);
                // return !node.isParent;
                return true;
            }


            //查询事件
            var searchText;
            $scope.searchData = function () {
                if ($scope.searchText == "" || $scope.searchText == "*") {
                    initTree();
                } else {
                    if ($scope.searchType) {
                        var searchText = '"' + $scope.searchText + '"'
                    } else {
                        var searchText = $scope.searchText
                    }
                    refreshTree(searchText);
                }
                $scope.search();
            }
            $scope.resetData = function () {
                $scope.searchText = "*"
                $scope.search();
            }
            $scope.search = function () {
                if (!$scope.searchText) {
                    // toastr.info('请输入查询内容！');
                    // return;
                    $scope.searchText = "*"
                }
                console.log($scope.searchType)
                var searchText;
                if ($scope.searchType) {
                    searchText = '"' + $scope.searchText + '"';
                } else {
                    searchText = $scope.searchText;
                }
                //重置查询结果
                $scope.tableData = [];
                $scope.paginationConf.totalItems = 0;
                //存储页面参数
                $location.search({
                    'searchText': $scope.searchText,
                    'searchType': $scope.searchType,
                    'currentPage': $scope.paginationConf.currentPage,
                    'itemsPerPage': $scope.paginationConf.itemsPerPage
                });
                //按文件库过滤
                console.log($scope.searchFilter.folder)
                if ($scope.searchFilter.folder) {
                    //查询内容
                    $scope.searchFilter.text = searchText;
                    //按时间过滤
                    if ($scope.searchFilter.time != "all") {
                        $scope.searchFilter.text += ' when:' + $scope.searchFilter.time
                    }
                    //按标签过滤
                    if ($scope.searchFilter.tag != "") {
                        $scope.searchFilter.text += ' tags:' + $scope.searchFilter.tag
                    }
                    //按文件类型过滤
                    if ($scope.searchFilter.type == "word") {
                        getResultData($scope.searchFilter.text + ' filename:*/' + $scope.searchFilter.folder + '/*.doc');
                        getResultData($scope.searchFilter.text + ' filename:*/' + $scope.searchFilter.folder + '/*.docx');
                    } else if ($scope.searchFilter.type == "img") {
                        getResultData($scope.searchFilter.text + ' filename:*/' + $scope.searchFilter.folder + '/*.jpg');
                        getResultData($scope.searchFilter.text + ' filename:*/' + folde$scope.searchFilter.folderrNames + '/*.jpeg');
                        getResultData($scope.searchFilter.text + ' filename:*/' + $scope.searchFilter.folder + '/*.png');
                    } else if ($scope.searchFilter.type == "data") {
                        getResultData($scope.searchFilter.text + ' filename:*/' + $scope.searchFilter.folder + '/*.xls');
                        getResultData($scope.searchFilter.text + ' filename:*/' + $scope.searchFilter.folder + '/*.xlsx');
                        getResultData($scope.searchFilter.text + ' filename:*/' + $scope.searchFilter.folder + '/*.csv');
                        getResultData($scope.searchFilter.text + ' filename:*/' + $scope.searchFilter.folder + '/*.json');
                    } else if ($scope.searchFilter.type != "all") {
                        $scope.searchFilter.text += ' filename:*/' + $scope.searchFilter.folder + '/*.' + $scope.searchFilter.type
                        getResultData($scope.searchFilter.text);
                    } else {
                        $scope.searchFilter.text += ' filename:*/' + $scope.searchFilter.folder + '/*'
                        getResultData($scope.searchFilter.text);
                    }

                } else {
                    //查询内容
                    $scope.searchFilter.text = $scope.searchText;
                    //按时间过滤
                    if ($scope.searchFilter.time != "all") {
                        $scope.searchFilter.text += ' when:' + $scope.searchFilter.time;
                    }
                    //按标签过滤
                    if ($scope.searchFilter.tag != "") {
                        $scope.searchFilter.text += ' tags:' + $scope.searchFilter.tag;
                    }
                    //按文件类型过滤
                    if ($scope.searchFilter.type == "word") {
                        getResultData($scope.searchFilter.text + ' filename:*.doc');
                        getResultData($scope.searchFilter.text + ' filename:*.docx');
                    } else if ($scope.searchFilter.type == "img") {
                        getResultData($scope.searchFilter.text + ' filename:*.jpg');
                        getResultData($scope.searchFilter.text + ' filename:*.jpeg');
                        getResultData($scope.searchFilter.text + ' filename:*.png');
                    } else if ($scope.searchFilter.type == "data") {
                        getResultData($scope.searchFilter.text + ' filename:*.csv');
                        getResultData($scope.searchFilter.text + ' filename:*.json');
                    } else if ($scope.searchFilter.type != "all") {
                        $scope.searchFilter.text += ' filename:' + $scope.searchFilter.type
                        getResultData($scope.searchFilter.text);
                    } else {
                        getResultData($scope.searchFilter.text);
                    }
                }



            }

            // 获取查询得到的结果列表数据
            function getResultData(text) {
                console.log(text)
                $http({
                    url: API_SERVICE_AMBAR + 'api/search',//发送请求的url路径  
                    method: 'GET',
                    params: {
                        query: text,
                        page: $scope.paginationConf.currentPage - 1,
                        size: $scope.paginationConf.itemsPerPage
                    }
                }).success(function (response, status, header, config, statusText) {
                    console.log("response.hits", response.hits);
                    $scope.tableData = $scope.tableData.concat(response.hits); //当前分页的每页显示的记录数

                    //console.log("$scope.tableData", $scope.tableData);
                    // 数据转换
                    for (let i = 0; i < $scope.tableData.length; i++) {
                        if ($scope.tableData[i].content.size <= 1024) { //小于等于1KB
                            $scope.tableData[i].content.size = $scope.tableData[i].content.size + "bytes";
                        } else if ($scope.tableData[i].content.size > 1024 && $scope.tableData[i].content.size <= 1024 * 1024) { //大于1KB小于等于1MB
                            $scope.tableData[i].content.size = ($scope.tableData[i].content.size / 1024).toFixed(2) + "KB";
                        } else if ($scope.tableData[i].content.size > 1024 * 1024 && $scope.tableData[i].content.size <= 1024 * 1024 * 1024) { //大于1MB小于等于1GB
                            $scope.tableData[i].content.size = (($scope.tableData[i].content.size / 1024) / 1024).toFixed(2) + "MB";
                        } else if ($scope.tableData[i].content.size > 1024 * 1024 * 1024) {
                            $scope.tableData[i].content.size = ((($scope.tableData[i].content.size / 1024) / 1024) / 1024) + "GB";
                        }
                    }
                    $scope.paginationConf.totalItems += response.total; //查询得到的总记录数
                    //console.log($scope.tableData);
                    angular.forEach($scope.tableData, function (date, index) {
                        date.picUrl = "";
                        date.showes = false;
                        date.openInfo = true;//是否打开摘要
                        date.up = true;//关闭摘要向上标识
                        date.down = false;//打开摘要向下标识
                        date.wordCssto = "";//文件logo样式
                        date.wordCsstext = "";

                    });



                    //  console.log("response.hits", response.hits);
                    for (var i = 0; i < $scope.tableData.length; i++) {
                        if ($scope.tableData[i].content.thumb_available) {
                            $scope.tableData[i].picUrl = "asd.png";
                        } else {
                            $scope.tableData[i].picUrl = "asp.png";
                        }
                        //添加文件logocss样式
                        for (var j = 0; j < $scope.wordCss.length; j++) {

                            if ($scope.tableData[i].meta.extension.slice(1) == $scope.wordCss[j]) {
                                $scope.tableData[i].wordCssto = $scope.tableData[i].meta.extension.slice(1);
                                $scope.tableData[i].wordCsstext = $scope.tableData[i].meta.extension.slice(1);
                                break;

                            } else {
                                $scope.tableData[i].wordCssto = "other";
                                $scope.tableData[i].wordCsstext = $scope.tableData[i].meta.extension.slice(1);

                            }

                        }

                    }


                }).error(function (data, header, config, status) {
                    toastr.error('查询失败！');
                });
            }

            $scope.tags = []; //存放经过归类的标签对象
            $scope.httpTags = []; //存放来自服务器的标签数据
            $scope.classifiedTags = []; //存放分类标签
            // 初始化
            function init() {
                //获取标签
                $http({
                    url: API_SERVICE_AMBAR + 'api/tags',
                    method: 'GET'
                }).success(function (response, status, header, config, statusText) {
                    $scope.byTag = response;
                    console.log("tags", $scope.byTag);
                    // var tagsFromHttp = angular.copy(response); //复制一份对象数组
                    var tagsFromHttp = [];
                    $scope.byTag.forEach(function (data) {
                        if (data.type != 'manual') {
                            tagsFromHttp.push(data)
                        }
                    })
                    var tagsFromHttpCopy = angular.copy(tagsFromHttp);
                    // 将标签进行归类
                    sortOut(tagsFromHttpCopy); //分类显示在文件标签
                    sortOutTags(tagsFromHttp); //显示在添加标签菜单中
                    console.log("$scope.tags", $scope.tags);
                    $scope.httpTags = angular.copy(response);
                }).error(function (data, header, config, status) {
                    toastr.error('查询失败！');
                });

                if ($scope.searchText == "" || $scope.searchText == "*") {
                    initTree()
                } else {
                    if ($scope.searchType) {
                        var searchText = '"' + $scope.searchText + '"'
                    } else {
                        var searchText = $scope.searchText
                    }
                    refreshTree(searchText)
                    // refreshTree($scope.searchText)
                }

            }
            init();

            // 将标签名称按所属标签类型进行归类
            function sortOut(jsonData) {
                if (jsonData.length > 1) {
                    $scope.tagObj = {};
                    $scope.tagObj.tagNames = [];
                    $scope.tagObj.tagType = jsonData[0].type; //存放数组的第一个标签对象，用来和数组其余的对象进行标签类型的比较
                    $scope.tagObj.tagNames.push(jsonData[0].name);
                    $scope.tagObj.id = (Math.random() * 10000000).toString(16).substr(0, 4) + '_' + (new Date()).getTime() + '_' + Math.random().toString().substr(2, 5); //生成唯一的编码
                    $scope.tags.push($scope.tagObj);
                    jsonData.splice(0, 1); //删除此元素

                    for (let i = 0; i < $scope.tags.length; i++) {
                        for (let j = 0; j < jsonData.length; j++) {
                            if ($scope.tags[i].tagType == jsonData[j].type) {
                                $scope.tags[i].tagNames.push(jsonData[j].name);
                                jsonData.splice(j, 1);
                                check($scope.tags[i], jsonData);
                            }
                        }
                    }
                    sortOut(jsonData);
                } else if (jsonData.length == 1) {
                    $scope.tagObj = {};
                    $scope.tagObj.tagNames = [];
                    $scope.tagObj.tagType = jsonData[0].type; //存放数组的第一个标签对象，用来和数组其余的对象进行标签类型的比较
                    $scope.tagObj.tagNames.push(jsonData[0].name);
                    $scope.tagObj.id = (Math.random() * 10000000).toString(16).substr(0, 4) + '_' + (new Date()).getTime() + '_' + Math.random().toString().substr(2, 5); //生成唯一的编码
                    $scope.tags.push($scope.tagObj);
                    jsonData.splice(0, 1); //删除此元素
                    console.log("jsonData", jsonData);
                    return false;
                } else {
                    return false;
                }
            }

            function sortOutTags(TagData) {
                if (TagData.length > 1) {
                    $scope.tagObj = {};
                    $scope.tagObj.tagNames = [];
                    $scope.tagObj.tagType = TagData[0].type; //存放数组的第一个标签对象，用来和数组其余的对象进行标签类型的比较
                    $scope.tagObj.tagNames.push(TagData[0].name);
                    $scope.tagObj.id = (Math.random() * 10000000).toString(16).substr(0, 4) + '_' + (new Date()).getTime() + '_' + Math.random().toString().substr(2, 5); //生成唯一的编码
                    $scope.classifiedTags.push($scope.tagObj);
                    TagData.splice(0, 1); //删除此元素

                    for (let i = 0; i < $scope.classifiedTags.length; i++) {
                        for (let j = 0; j < TagData.length; j++) {
                            if ($scope.classifiedTags[i].tagType == TagData[j].type) {
                                $scope.classifiedTags[i].tagNames.push(TagData[j].name);
                                TagData.splice(j, 1);
                                check($scope.classifiedTags[i], TagData);
                            }
                        }
                    }
                    sortOutTags(TagData);
                } else if (TagData.length == 1) {
                    $scope.tagObj = {};
                    $scope.tagObj.tagNames = [];
                    $scope.tagObj.tagType = TagData[0].type; //存放数组的第一个标签对象，用来和数组其余的对象进行标签类型的比较
                    $scope.tagObj.tagNames.push(TagData[0].name);
                    $scope.tagObj.id = (Math.random() * 10000000).toString(16).substr(0, 4) + '_' + (new Date()).getTime() + '_' + Math.random().toString().substr(2, 5); //生成唯一的编码
                    $scope.classifiedTags.push($scope.tagObj);
                    TagData.splice(0, 1); //删除此元素
                    return false;
                } else {
                    return false;
                }
            }

            function check(data_1, data_2) {
                for (let k = 0; k < data_2.length; k++) {
                    if (data_1.tagType == data_2[k].type) {
                        data_1.tagNames.push(data_2[k].name);
                        data_2.splice(k, 1);
                        check(data_1, data_2);
                    }
                }
            }

            //查询条件为*时，显示树
            function initTree() {
                console.log("initTree")
                //树宽度
                $scope.Ulwidth = document.getElementById("zTreeBox").clientWidth || document.getElementById("zTreeBox").offsetWidth;
                console.log($scope.Ulwidth)
                $scope.byFolder = []; //存储文件夹节点
                $scope.folderNames = []; //存储文件夹节点名字
                $scope.treeFolderData = []
                // 获取文件库
                $http.get(API_SERVICE_AMBAR + "api/search/tree?query=*%20filename://crawler-files/*").then(function (response) {
                    //爬虫文件目录
                    if (response.data.tree.length > 0) {
                        response.data.tree[0].children.forEach(function (data, index) { //二级目录
                            if (data.type != 'file') {
                                data.folderNames = [];
                                data.children.forEach(function (subData, subIndex) { //三级目录
                                    data.folderNames.push(subData.name)
                                })
                                $scope.byFolder.push(data)
                                $scope.folderNames.push(data.name)
                            }
                        }, this)
                        //上传文件目录
                        $http.get(API_SERVICE_AMBAR + "api/search/tree?query=*%20filename://upload-files/*").then(function (response) {
                            if (response.data.tree.length > 0) {
                                response.data.tree[0].children.forEach(function (data, index) {
                                    if (data.type != 'file') {
                                        if ($scope.folderNames.indexOf(data.name) == -1) { //二级目录去重与合并
                                            data.folderNames = [];
                                            data.children.forEach(function (subData, subIndex) { //三级目录
                                                data.folderNames.push(subData.name)
                                            })
                                            $scope.byFolder.push(data)
                                            $scope.folderNames.push(data.name)
                                        } else {
                                            $scope.byFolder.forEach(function (folder, folder_index) { //三级目录去重与合并
                                                if (folder.name == data.name) {
                                                    folder.hits_count = folder.hits_count + data.hits_count
                                                    data.children.forEach(function (subData, subIndex) {
                                                        if (folder.folderNames.indexOf(subData.name) == -1) {
                                                            folder.children.push(subData)
                                                            folder.folderNames.push(subData.name)
                                                        } else {
                                                            var index = folder.folderNames.indexOf(subData.name)
                                                            folder.children[index].hits_count = folder.children[index].hits_count + subData.hits_count
                                                        }
                                                    })

                                                }
                                            }, this)
                                        }
                                    }
                                }, this)
                            }
                            treeShow()

                        });
                    } else {
                        //上传文件目录
                        $http.get(API_SERVICE_AMBAR + "api/search/tree?query=*%20filename://upload-files/*").then(function (response) {
                            if (response.data.tree.length > 0) {
                                response.data.tree[0].children.forEach(function (data, index) { //二级目录
                                    if (data.type != 'file') {
                                        data.folderNames = [];
                                        data.children.forEach(function (subData, subIndex) { //三级目录
                                            data.folderNames.push(subData.name)
                                        })
                                        $scope.byFolder.push(data)
                                        $scope.folderNames.push(data.name)
                                    }
                                }, this)
                                treeShow()
                            } else {
                                $scope.treeFolderData = [];
                            }


                        });
                    }
                });

            }
            function refreshTree(text) {
                //树宽度
                $scope.Ulwidth = document.getElementById("zTreeBox").clientWidth || document.getElementById("zTreeBox").offsetWidth;
                console.log($scope.Ulwidth)
                $scope.byFolder = []; //存储文件夹节点
                $scope.folderNames = []; //存储文件夹节点名字
                $scope.treeFolderData = []
                // 获取文件库
                $http({
                    url: API_SERVICE_AMBAR + 'api/search/tree',//发送请求的url路径  
                    method: 'GET',
                    params: {
                        query: text,
                    }
                }).success(function (response, status, header, config, statusText) {
                    console.log("response.tree", response.tree);
                    if (response.tree.length > 0) {
                        response.tree.forEach(function (tree) {
                            tree.children.forEach(function (data, index) {
                                if (data.type != 'file') {
                                    if ($scope.folderNames.indexOf(data.name) == -1) { //二级目录去重与合并
                                        data.folderNames = [];
                                        data.children.forEach(function (subData, subIndex) { //三级目录
                                            data.folderNames.push(subData.name)
                                        })
                                        $scope.byFolder.push(data)
                                        $scope.folderNames.push(data.name)
                                    } else {
                                        $scope.byFolder.forEach(function (folder, folder_index) { //三级目录去重与合并
                                            if (folder.name == data.name) {
                                                folder.hits_count = folder.hits_count + data.hits_count
                                                data.children.forEach(function (subData, subIndex) {
                                                    if (folder.folderNames.indexOf(subData.name) == -1) {
                                                        folder.children.push(subData)
                                                        folder.folderNames.push(subData.name)
                                                    } else {
                                                        var index = folder.folderNames.indexOf(subData.name)
                                                        folder.children[index].hits_count = folder.children[index].hits_count + subData.hits_count
                                                    }
                                                })

                                            }
                                        }, this)
                                    }
                                }
                            }, this)
                        })
                        treeShow()
                    } else {
                        $scope.treeFolderData = [];
                    }
                }).error(function (data, header, config, status) {
                    toastr.error('查询失败！');
                });


            }

            // 树节点处理 - 页面显示
            function treeShow() {
                //页面显示
                $scope.byFolder.forEach(function (data, index) {
                    var obj = angular.copy(data)
                    obj['parent_path'] = obj['parent_path'].replace(/crawler-files/g, 'upload-files');
                    obj['path'] = obj['path'].replace(/crawler-files/g, 'upload-files');
                    obj.children = []
                    obj.folderName = obj.name
                    // obj.name = obj.name + ' ' + obj.hits_count
                    var index = Math.floor(($scope.Ulwidth - 60) / 15)
                    obj.title = obj.name + '（' + obj.hits_count + '）'
                    if (obj.name.length > index) {
                        // obj.name = obj.name.substring(0, index) + '…（' + obj.hits_count + '）'
                        obj.name = obj.name.substring(0, index) + "…" + "<span class='dataNumByFolder'>" + '（' + obj.hits_count + '）' + "</span>";
                    } else {
                        // obj.name = obj.name + '（' + obj.hits_count + '）'
                        obj.name = obj.name + "<span class='dataNumByFolder'>" + '（' + obj.hits_count + '）' + "</span>";
                    }
                    $scope.treeFolderData.push(obj)
                    if (data.children.length > 0) {
                        checkHasChildren(data.children)
                    }
                }, this)
                //zTree树数据排序
                $scope.treeFolderData.forEach(function (data, index) {
                    var arry = data.name.split('.')
                    var order = parseInt(arry[0])
                    if (isNaN(order)) {
                        data.order = $scope.treeFolderData.length
                    } else {
                        data.order = order
                    }
                }, this)
                var treeData = $scope.treeFolderData.sort(function (a, b) {
                    return parseInt(a.order) - parseInt(b.order);
                });
                $scope.treeFolderData = treeData;
                $(document).ready(function () {
                    console.log("$scope.treeFolderData", $scope.treeFolderData)
                    $.fn.zTree.init($("#zTreeBox"), $scope.treeSetting, $scope.treeFolderData);
                    zTree_Menu = $.fn.zTree.getZTreeObj("zTreeBox");
                    console.log("zTree_Menu", zTree_Menu);
                    curMenu = zTree_Menu.getNodes()[0]
                    if (zTree_Menu.getNodes()[0].children.length > 0) {
                        curMenu = zTree_Menu.getNodes()[0].children[0]
                    }
                    // if(zTree_Menu.getNodes()[0].children[0].children.length>0){
                    //     curMenu = zTree_Menu.getNodes()[0].children[0].children[0];
                    // }
                    // curMenu = zTree_Menu.getNodes()[0].children[0].children[0];
                    for (var i = 0; i < zTree_Menu.getNodes().length; i++) {
                        var nodes = zTree_Menu.getNodes()[i].children;
                        curMenu = zTree_Menu.getNodes()[i];
                        if (nodes.length > 0 && nodes != null) {
                            $("#" + curMenu.tId + "_a.level0").addClass('hasChildren');
                        }
                    }
                    var a0 = $(".ztree li a span.node_name");
                    a0.hover(function(){
                        $(this.children).css({"color":"#fff"});
                    },function(){
                        $(this.children).removeAttr("style","");
                        // $(this.children).css({"color":"red"});
                    });
                    console.log("curMenu", curMenu);
                    // zTree_Menu.selectNode(curMenu);
                    // var a = $("#" + zTree_Menu.getNodes()[0].tId + "_a");
                    // a.addClass("cur");
                });
            };


            // 遍历当前节点是否还有子节点并且判断子节点是否是file类型的方法
            function checkHasChildren(treeData) {
                treeData.forEach(function (data, index) {
                    if (data.type != 'file') {
                        var obj = angular.copy(data)
                        obj['parent_path'] = obj['parent_path'].replace(/crawler-files/g, 'upload-files');
                        obj['path'] = obj['path'].replace(/crawler-files/g, 'upload-files');
                        obj.children = []
                        obj.name = obj.name.replace(/^\s+/, '').replace(/\s+$/, '');
                        obj.folderName = obj.name;
                        obj.name = obj.name + '（' + obj.hits_count + '）'
                        obj.title = obj.name
                        $scope.treeFolderData.push(obj)
                        if (data.children.length > 0) {
                            checkHasChildren(data.children)
                        }
                    }
                }, this)
            };

            //控制查询条件显示或者隐藏
            $scope.visible = true;
            $scope.open = function () {
                $scope.visible = !$scope.visible;
            }

            //按文件类型过滤
            $scope.typeFilter = function (value) {
                $scope.searchFilter.type = value;
                if ($scope.paginationConf.currentPage != 1) {
                    $scope.paginationConf.currentPage = 1;
                } else {
                    $scope.search()
                }
            }

            //按时间过滤
            $scope.tagFilter = function (value) {
                if ($scope.searchFilter.tag == value) {
                    $scope.searchFilter.tag = "";
                } else {
                    $scope.searchFilter.tag = value;
                }
                if ($scope.paginationConf.currentPage != 1) {
                    $scope.paginationConf.currentPage = 1;
                } else {
                    $scope.search()
                }
            }

            //按标签过滤
            $scope.timeFilter = function (value) {
                $scope.searchFilter.time = value;
                if ($scope.paginationConf.currentPage != 1) {
                    $scope.paginationConf.currentPage = 1;
                } else {
                    $scope.search()
                }
            }

            //按文件库过滤
            $scope.folderFilter = function (value) {
                if ($scope.searchText == "" || $scope.searchText == "*") {
                    initTree()
                } else {
                    if ($scope.searchType) {
                        var searchText = '"' + $scope.searchText + '"'
                    } else {
                        var searchText = $scope.searchText
                    }
                    refreshTree(searchText)
                    // refreshTree($scope.searchText)
                }
                $scope.searchFilter.folder = value;
                if ($scope.paginationConf.currentPage != 1) {
                    $scope.paginationConf.currentPage = 1;
                } else {
                    $scope.search()
                }
            }
            // $scope.folderShow = function ($event, data) {
            //     $event.stopPropagation();//阻止事件冒泡
            //     if (data.check) {
            //         data.check = false
            //         var index = $scope.searchFilter.folder.indexOf(data.name)
            //         $scope.searchFilter.folder.splice(index, 1)
            //     }
            //     data.show = !data.show
            //     console.log($scope.searchFilter.folder)
            // }
            // $scope.folderFilter = function ($event, data) {
            //     $event.stopPropagation();//阻止事件冒泡
            //     data.check = !data.check
            //     data.show = false
            //     if (data.check) {
            //         if ($scope.searchFilter.folder.indexOf(data.name) == -1) { //二级目录去重与合并
            //             $scope.searchFilter.folder.push(data.name)
            //         }
            //     } else {
            //         var index = $scope.searchFilter.folder.indexOf(data.name)
            //         $scope.searchFilter.folder.splice(index, 1)
            //     }
            //     console.log($scope.searchFilter.folder)
            //     $scope.search()
            // }

            //跳转到详情页
            $scope.Todetail_Infomation = function (file) {
                $state.go('app.files-text', {
                    paramsObj: file.file_id,
                    search_text: $scope.searchText
                });
                console.log(file.file_id, $scope.searchText);
            }

            $scope.showFileDetails = function (file) {
                //console.log(file.file_id);
                $http({
                    url: API_SERVICE_AMBAR + 'api/search' + '/' + file.file_id + '/' + 'full', //发送请求的url路径  
                    method: 'GET', //取值为GET/DELETE/HEAD/JSONP/POST/PUT，是字符串  
                    params: {
                        'query': $scope.searchText //$stateParams.paramsObj
                    }
                }).success(function (response, status, header, config, statusText) {
                    //成功处理  
                    console.log(response);
                    $scope.fullcontent = response;
                    // console.log($scope.files);


                }).error(function (data, header, config, status) {
                    //错误处理  
                });
                $scope.fileName = file.meta.short_name;

            }

            $scope.PreviewImg = function (file) {//点击预览图片
                $scope.Viewer = new Viewer(document.getElementById(file.meta.id), {
                    //参数配置 http://www.dowebok.com/192.html
                    url: 'data-original',
                });
            }


            $scope.PreviewImg1 = function (id) {//点击预览图片
                $scope.Viewer = new Viewer(document.getElementById(id), {
                    //参数配置 http://www.dowebok.com/192.html
                    url: 'data-original1',
                    //console.log();
                });

            }
            $scope.showes = false;
            $scope.showsh = function (file) {
                file.showes = !file.showes;
            }
            //控制摘要是否显示
            $scope.openUp = function (file) {
                file.up = false;
                file.down = true;
                file.openInfo = false;
            }
            $scope.openDown = function (file) {
                file.up = true;
                file.down = false;
                file.openInfo = true;

            }
            $scope.openAll = function () {
                for (var i = 0; i < $scope.tableData.length; i++) {

                    $scope.tableData[i].openInfo = true;
                    $scope.tableData[i].up = true;
                    $scope.tableData[i].down = false;
                }

            }
            $scope.closeAll = function () {
                for (var i = 0; i < $scope.tableData.length; i++) {

                    $scope.tableData[i].openInfo = false;
                    $scope.tableData[i].up = false;
                    $scope.tableData[i].down = true;
                }

            }

            // 删除文件
            $scope.delete = function (file) {
                console.log(file);
                sweetAlert(
                    {
                        title: "您确定删除此文件吗？",
                        text: file.meta['short_name'],
                        type: "warning",
                        showCancelButton: true,
                        confirmButtonColor: "#DD6B55",
                        confirmButtonText: "确定",
                        cancelButtonText: "取消"
                    }, function () {
                        $http({
                            url: API_SERVICE_AMBAR + 'api/files/hide/' + file.file_id,//发送请求的url路径  
                            method: 'put',
                        }).success(function (response) {
                            // location.reload();
                            $scope.search()
                            console.log(response);
                        }).error(function (err) {
                            console.log(err);
                        });

                    });
            }

            // 下载文件
            $scope.download = function (file) {
                // console.log("download", file);
                window.open((API_SERVICE_AMBAR + 'api/files/download?path=' + file.meta.full_name));
            }

            // 显示标签菜单
            /* 
                @tags 当前文件已有的标签名称数组
                @index 当前文件的索引
            */
            $scope.curTagMenuId = null;
            $scope.showAddedTags = function (tags, index, tableDataArr, file) {
                $("body").unbind("mousedown", onBodyMouseDown);
                for (let i = 0; i < tableDataArr.length; i++) {
                    if (i == index) {
                        if (document.getElementById("tagMenu" + index).style.visibility == "hidden") {
                            $scope.curTagMenuId = index;
                            $("body").bind("mousedown", onBodyMouseDown);
                            document.getElementById("tagMenu" + index).style.visibility = 'visible';
                            continue;
                        } else {
                            document.getElementById("tagMenu" + index).style.visibility = 'hidden';
                            continue;
                        }
                    }
                    var tagMenuItem = document.getElementById("tagMenu" + i);
                    tagMenuItem.style.visibility = "hidden";
                }
                console.log("显示添加标签的菜单", tags);
                $scope.tagsInMenu = []; //存放标签菜单的数组对象
                $scope.tagsInMenu = angular.copy($scope.httpTags);
                /* 
                    将当前文件中已有的标签名称，和来自服务器并且经过过滤的标签名称进行比较
                    如果当前文件中不存在服务器的标签名称，则将不存在的标签名称显示在添加标签按钮的弹出菜单中
                */
                for (let i = 0; i < tags.length; i++) {
                    for (let j = 0; j < $scope.tagsInMenu.length;) {
                        if ($scope.tagsInMenu[j].name == tags[i].name && $scope.tagsInMenu[j].type == tags[i].type) {
                            $scope.tagsInMenu.splice(j, 1);
                            j = 0; //重新开始比较
                        } else {
                            j++;
                        }
                    }
                }
                // $scope.tagsInMenu.splice($scope.tagsInMenu.length - 1, 1);
                console.log("$scope.tagsInMenu", $scope.tagsInMenu);
                // 获取标签菜单
                var tagMenu = document.getElementById("tagMenu" + index);
                console.log(tagMenu);
                // alert(tagMenu.style.visibility);
                // if(tagMenu.style.visibility == "hidden"){
                //     tagMenu.style.visibility = "visible";
                // }else{
                //     tagMenu.style.visibility = "hidden";
                // }
                // 默认显示第一个标签类型
                $scope.showSelectedTagTypes($scope.classifiedTags[0], file);         
            }

            // 显示标签类型和对应的属于该类型的标签名称
            $scope.showSelectedTagTypes = function (tagType, file) {
                $scope.tagTypeForSelect = angular.copy(tagType);
                console.log("当前的文件已有的标签", file);
                for (let i = 0; i < file.tags.length; i++) {
                    for (let j = 0; j < $scope.tagTypeForSelect.tagNames.length;) {
                        if ($scope.tagTypeForSelect.tagNames[j] == file.tags[i].name) {
                            $scope.tagTypeForSelect.tagNames.splice(j, 1);
                            j = 0;
                        } else {
                            j++;
                        }
                    }
                }
            }

            $scope.addTag = function (tagType, tagName, file, index) {
                $("body").unbind("mousedown", onBodyMouseDown);
                $http({
                    url: API_SERVICE_AMBAR + 'api/tags/' + file.file_id + '/' + tagType.tagType + '/' + tagName,
                    method: 'post'
                }).success(function (response) {
                    var tagMenu = document.getElementById("tagMenu" + index);
                    tagMenu.style.visibility = "hidden";
                    console.log("添加标签ok");
                    /* 
                        为了方便在添加标签之后，在页面当中显示，故构造成统一的数据格式
                    */
                    var newTagObj = {};
                    newTagObj.type = tagType.tagType;
                    newTagObj.name = tagName;
                    file.tags.push(newTagObj);
                }).error(function (err) {
                    toastr.error("添加标签失败！");
                });
            }

            $scope.newAddedTags = []; //记录新添加的标签
            // 添加标签
            $scope.addTagItem = function (tag, file, index) {
                $("body").unbind("mousedown", onBodyMouseDown);
                $http({
                    url: API_SERVICE_AMBAR + 'api/tags/' + file.file_id + '/' + tag.type + '/' + tag.name,
                    method: 'post'
                }).success(function (response) {
                    var tagMenu = document.getElementById("tagMenu" + index);
                    tagMenu.style.visibility = "hidden";
                    console.log("添加标签ok");
                    file.tags.push(tag);
                }).error(function (err) {
                    toastr.error("添加标签失败！");
                });

            }

            // 鼠标点击事件
            function onBodyMouseDown(event) {
                console.log("event.target.id", event.target.id);
                console.log("$scope.curTagMenuId", $scope.curTagMenuId);
                if (!(event.target.id == ("tagMenu" + $scope.curTagMenuId) || $(event.target).parents("#tagMenu" + $scope.curTagMenuId).length > 0 || event.target.id == ("showAddedTags" + $scope.curTagMenuId))) {
                    document.getElementById("tagMenu" + $scope.curTagMenuId).style.visibility = 'hidden';
                }
                // document.getElementById("tagMenu"+$scope.curTagMenuId).style.visibility = 'hidden';
                // for(let i = 0; i < tableDataArr.length; i++){
                //     var tagMenuItem = document.getElementById("tagMenu"+i);
                //     tagMenuItem.style.visibility = "hidden";
                // }
            };

            // 删除标签
            /* 
                @tag 新增的标签名称
                @fileId 当前文件Id
            */
            $scope.deleteOldTagItem = function (tag, file) {
                console.log("删除", file['file_id']);
                $http({
                    url: API_SERVICE_AMBAR + 'api/tags/' + file['file_id'] + '/' + tag.type + '/' + tag.name,
                    method: 'delete'
                }).success(function (response) {
                    console.log("删除标签ok");
                    for (let i = 0; i < file.tags.length; i++) {
                        if (tag.name == file.tags[i].name && tag.type == file.tags[i].type) {
                            file.tags.splice(i, 1);
                            return false; //不再往下执行，提高性能
                        }
                    }
                }).error(function (err) {
                    toastr.error("删除标签失败！");
                })
            }
        }
    ]);
    // 显示html文件过滤器
    appModule.filter('to_trusted', ['$sce', function ($sce) {
        return function (text) {
            return $sce.trustAsHtml(text);
        };
    }]);
})();
